/**
 * 将树形结构的数据，转换为可以循环渲染的数组
 */
import line from './line'

const NAMESPACE = 'COLUMN_'

// 设置值，控制向前还是向后插入数组，并且记录起始点
function setItems(items, columnsMap, index, customKeys) {
  // defind empty array
  const key = NAMESPACE + index
  if (columnsMap[key] === undefined) {
    columnsMap[key] = []
  }
  // iterator items
  items.forEach(item => {
    columnsMap[key].push({
      uuid: item.uuid,
      data: item.data
    })
    if (item[customKeys.upstream] && item[customKeys.upstream].length) {
      setItems(item[customKeys.upstream], columnsMap, index - 1, customKeys)
    }
    if (item[customKeys.downstream] && item[customKeys.downstream].length) {
      setItems(item[customKeys.downstream], columnsMap, index + 1, customKeys)
    }
  })
}

function mapToArray (map) {
  const columns = []
  Object.keys(map)
  .sort((a, b) => {
    return getIndex(a) - getIndex(b)
  })
  .forEach(key => {
    columns.push(map[key])
  })
  return columns
}

function getIndex (key) {
  return Number.parseInt(key.replace(NAMESPACE, ''))
}

function transfer (source, customKeys) {
  
  if (source === null) return {columns: [], lines: []}

  const {data, lineArray} = line(source)
  const columnsMap = {[`${NAMESPACE}0`]: []}
  setItems([data], columnsMap, 0, customKeys)
  return {
    columns: mapToArray(columnsMap),
    lines: lineArray
  }
}

export default transfer
